package com.ibeeking.found.uaa.cp.service.impl;

import com.ibeeking.gmc.global.api.common.dto.OauthClientDTO;
import com.ibeeking.gmc.global.api.feign.GlobalOpenFeignClient;
import com.ibeeking.found.uaa.cp.constant.RedisKeyConstant;
import com.ibeeking.found.uaa.cp.model.ClientDetailsModel;

import com.ibeeking.nematos.redis.utils.RedisUtils;
import com.ibeeking.nematos.utils.json.JsonUtils;
import com.ibeeking.nematos.utils.result.ResponseResult;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * @ClassName CpClientDetailsServiceImpl
 * @Description
 * @Author ibeeking
 * @Date 2020-11-16 14:39
 **/
@Service("clientDetailsServiceImpl")
public class CpClientDetailsServiceImpl implements ClientDetailsService {

    private static final String CLIENT_ID = "CLIENT_ID_CP:";

    @Resource
    private GlobalOpenFeignClient globalOpenFeignClient;

    @Resource
    private RedisUtils redisUtils;

    @Override
    public ClientDetailsModel loadClientByClientId(String clientId) throws ClientRegistrationException {
        if (StringUtils.isEmpty(clientId)) {
            throw new OAuth2Exception("clientId不能为空");
        }
        Object o = redisUtils.get(CLIENT_ID + clientId);
        OauthClientDTO oauthClientDTO = null;
        if (null == o) {
            ResponseResult<OauthClientDTO> responseResult = globalOpenFeignClient.queryByClientId(clientId);
            if (null == responseResult.getData())  throw new OAuth2Exception("client客户端未授权!");
            oauthClientDTO = responseResult.getData();
            redisUtils.set(CLIENT_ID + clientId, JsonUtils.toJsonStr(oauthClientDTO), RedisKeyConstant.DAY);
        } else {
            oauthClientDTO = JsonUtils.fromJson(o.toString(), OauthClientDTO.class);
        }
        return new ClientDetailsModel(oauthClientDTO);
    }
}
